import {iMicroPageServiceProvideData} from "@peryl/micro-web";
import {createRenderHook, inject, onBeforeUnmount, provide} from "@peryl/react-compose";
import {iRenderUseParam} from "@peryl/react-compose/src/utils/createRenderHook";

/**
 * 页面渲染控制模块
 * @author  韦胜健
 * @date    2024.6.12 22:38
 */
export const MicroAppPageRender = (() => {

  const PROVIDER_NAME = '@@MicroAppPageRender';

  const useProvider = (pageServiceProvideData: iMicroPageServiceProvideData) => {
    const hooks = { onPageRender: createRenderHook<iMicroPageServiceProvideData>(), };
    const render = () => hooks.onPageRender.exec({ renderMetas: [], renderData: pageServiceProvideData });
    const refer = { hooks, render, pageServiceProvideData };
    provide(PROVIDER_NAME, refer);
    return refer;
  };

  const usePageRender = (renderUseParam: iRenderUseParam<iMicroPageServiceProvideData>): boolean => {
    const injection = inject(PROVIDER_NAME, null) as null | ReturnType<typeof useProvider>;
    if (!injection) {return false;}
    onBeforeUnmount(injection.hooks.onPageRender.use(renderUseParam));
    return true;
  };

  return {
    useProvider,
    usePageRender,
  };
})();

export type iMicroAppPageRenderRefer = ReturnType<typeof MicroAppPageRender.useProvider>

export const usePageRender = MicroAppPageRender.usePageRender;
